package main

import (
	"fmt"
	"sync"
)

type Stats struct {
	mu       sync.Mutex
	counters map[string]int
}

// Snapshot 错误写法 返回了内部对象，不在受到锁的保护
func (s *Stats) Snapshot() map[string]int {
	if !s.mu.TryLock() {
		panic("获取锁失败")
		return nil
	}
	defer s.mu.Unlock()
	return s.counters
}

// GoodSnapshot 正确写法 返回了内部对象，不在受到锁的保护
func (s *Stats) GoodSnapshot() map[string]int {
	if !s.mu.TryLock() {
		panic("获取锁失败")
		return nil
	}
	defer s.mu.Unlock()
	result := make(map[string]int, len(s.counters))
	for k, v := range s.counters {
		result[k] = v
	}
	return result
}

func main() {
	mp := make(map[string]int)
	mp["a"] = 1
	mp["b"] = 2
	mp["c"] = 3
	stats := Stats{counters: mp}
	snapshot := stats.GoodSnapshot()
	snapshot["a"] = 19
	fmt.Println(snapshot)
	fmt.Println(stats.counters)

}
